#include "SimpleHighscoreService.h"
#include <stdio.h>
#include <fstream>
#include "utils\Log.h"

SimpleHighscoreService::SimpleHighscoreService() : ds::Service("Highscore") , m_Score(0) , m_Highscore(0) , m_Updated(false) {
	readHighscore();
}


SimpleHighscoreService::~SimpleHighscoreService(void) {
}

void SimpleHighscoreService::initialize() {
	readHighscore();
}

void SimpleHighscoreService::setScore(int score) {
	m_Score = score;
	if ( m_Score > m_Highscore ) {
		m_Highscore = m_Score;
		m_Updated = true;
	}
	else {
		m_Updated = false;
	}
}

int SimpleHighscoreService::readHighscore() {
	std::fstream binary_file("score.his", std::ios::binary | std::ios::in);    
	m_Highscore = 0;
    if (binary_file.is_open()) {
        binary_file.read((char*)&m_Highscore, sizeof (int));
    }
    binary_file.close();
	LOG(logINFO) << "reading highscore " << m_Highscore;
	return m_Highscore;
}

void SimpleHighscoreService::saveHighscore() {
	LOG(logINFO) << "saving highscore " << m_Highscore;
	std::fstream binary_file("score.his", std::ios::out | std::ios::binary);    
    binary_file.write(reinterpret_cast<char *> (&m_Highscore), sizeof (int));    
    binary_file.close();
}

